package com.base.framework.base.filter;

import com.base.commons.utils.StringUtils;
import com.base.commons.web.utils.PropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * 字符节编码过滤器
 * Created by Irany(欧书剑) 2017/8/2 0002 22:14
 */
@WebFilter
public class CharacterEncodingFilter extends OncePerRequestFilter {
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public void setForceEncoding(boolean forceEncoding) {
        this.forceEncoding = forceEncoding;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
            request.setCharacterEncoding(this.encoding);

            if(this.forceEncoding) {
                response.setCharacterEncoding(this.encoding);
            }
        }

        filterChain.doFilter(request, response);
    }

    @Override
    protected void initFilterBean() throws ServletException {
        super.initFilterBean();

        Enumeration<String> parameterNames = getFilterConfig().getInitParameterNames();

        if (parameterNames != null && parameterNames.hasMoreElements()) {
            for (; parameterNames.hasMoreElements();) {
                String paramName = parameterNames.nextElement();

                if ("encoding".equals(paramName)) {
                    setEncoding(getFilterConfig().getInitParameter(paramName));
                } else if ("forceEncoding".endsWith(paramName)) {
                    setForceEncoding(StringUtils.isBooleanTrue(getFilterConfig().getInitParameter(paramName)));
                }
            }
        }

        System.setProperty("net.sf.ehcache.skipUpdateCheck", PropertyUtil.get("net.sf.ehcache.skipUpdateCheck", "true"));
    }

    private String encoding;
    private boolean forceEncoding = false;
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
}
